package com.redwine.app;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RadioButton;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.redwine.app.fragments.HomeFragment;
import com.redwine.app.fragments.MeFragment;
import com.redwine.app.fragments.MessageFragment;
import com.redwine.app.fragments.PublishedSourcesFragment;
import com.redwine.app.net.responses.SendMsgEvent;
import com.redwine.app.utils.Constants;
import com.redwine.app.utils.Global;
import com.redwine.app.utils.Settings;
import com.redwine.app.utils.Utils;
import com.umeng.message.IUmengCallback;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {


    private String[] tabs = new String[4];
    private PushAgent mPushAgent;
    //当前显示那个模块
    private int currentFragmentIndex;
    private Map<Integer, Fragment> fragmentMaps = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ViewUtils.inject(this);
        EventBus.getDefault().register(this);
        init(savedInstanceState);
    }

    private void init(Bundle savedInstanceState) {
        Display mDisplay = getWindowManager().getDefaultDisplay();
        Global.screen_w = mDisplay.getWidth();
        Global.screen_h = mDisplay.getHeight();
        mPushAgent = PushAgent.getInstance(getApplicationContext());
        Log.e("umengToken", "register");
        mPushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                Log.e("umengToken", "onSuccess" + deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
                Log.e("umengToken", "onFailure" + s1);
            }
        });

        mPushAgent.enable(new IUmengCallback() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onFailure(String s, String s1) {

            }
        });


        tabs[0] = getString(R.string.home);
        tabs[1] = getString(R.string.goods);
        tabs[2] = getString(R.string.message);
        tabs[3] = getString(R.string.me);
        mine = (RadioButton) findViewById(R.id.me_button);
        book = (RadioButton) findViewById(R.id.books_button);
        setupFragments(savedInstanceState);
    }


    //    下面是fragment的切换
    private void setupFragments(Bundle savedInstanceState) {
        if (fragmentMaps.size() != 4) {//往fragment的集合中添加fragment，这里可以动态添加。
            Fragment homeFragment = Fragment.instantiate(this, HomeFragment.class.getName());
            fragmentMaps.put(R.id.discovery_button, homeFragment);
            fragmentMaps.put(R.id.books_button,
                    Fragment.instantiate(this, PublishedSourcesFragment.class.getName()));
            fragmentMaps.put(R.id.firend_button, Fragment.instantiate(this, MessageFragment.class.getName()));
            fragmentMaps.put(R.id.me_button,
                    Fragment.instantiate(this, MeFragment.class.getName()));//跳转到修改后的我的个人中心
            //默认显示发现界面
            currentFragmentIndex = R.id.discovery_button;
        }

        if (savedInstanceState == null) {
            currentFragmentIndex = R.id.discovery_button;
        } else {
            currentFragmentIndex = savedInstanceState.getInt("tab");//获取RadioGroup对应的id
            while (getFragmentManager().getBackStackEntryCount() > 0) {
                getFragmentManager().popBackStack();//弹出栈，清空后台fragment
            }
        }

        Fragment fragment = fragmentMaps.get(currentFragmentIndex);
        getSupportFragmentManager().beginTransaction().add(R.id.fragments, fragment).show(fragment)
                .commitAllowingStateLoss();//和commit的效果一样，只不过不抛异常
    }


    private long exitTime = 0;

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Utils.showToast("再按一次退出程序");
                exitTime = System.currentTimeMillis();
                return true;
            }
        }
        if (keyCode == KeyEvent.KEYCODE_MENU) {//MENU键
            // 监控/拦截菜单键
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private RadioButton mine;//我的消息红点提示
    private RadioButton book;

    //广播接收者
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, final Intent intent) {
            String action = intent.getAction();
            if (action.equals(Constants.INTENT_USER_LOGGED_OUT)) {

            } else if (action.equals(Constants.SELSECT_MINE)) {
                switchFragment(mine);
            } else if (action.equals(Constants.SELSECT_BOOK)) {
                switchFragment(book);
            }
        }
    };


    Intent intent;

    @OnClick({R.id.discovery_button, R.id.books_button, R.id.firend_button, R.id.me_button, R.id.senddt_button})
    public void mClick(View v) {
        switch (v.getId()) {
            case R.id.discovery_button:

                switchFragment(v);
                break;
            case R.id.books_button:

                switchFragment(v);
                break;
            case R.id.firend_button:

                switchFragment(v);
                break;
            case R.id.me_button:
                intent = new Intent(Constants.ME_FRAGMENT);
                LocalBroadcastManager.getInstance(APP.getInstance()).sendBroadcast(intent);
                switchFragment(v);
                break;
            case R.id.senddt_button:
                showDialog();
                break;
        }
    }

    private void switchFragment(View v) {
        if (currentFragmentIndex == v.getId()) {
            return;//选中的是同一个就不跳转
        }
        int id = v.getId();
        Fragment fragment1 = fragmentMaps.get(id);
        Fragment fragment2 = fragmentMaps.get(currentFragmentIndex);
        android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        if (!fragment1.isAdded()) {
            fragmentTransaction.add(R.id.fragments, fragment1);
        }
        fragmentTransaction.hide(fragment2).show(fragment1).commitAllowingStateLoss();

        currentFragmentIndex = id;
        RadioButton button = (RadioButton) findViewById(id);
        button.setChecked(true);//代码设置当前radiobutton为选中状态
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        outState.putInt("tab", currentFragmentIndex);
        super.onSaveInstanceState(outState);
    }


    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        android.support.v4.app.FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        for (int i = 0; i < 4; i++) {
            Fragment fragment = supportFragmentManager.findFragmentByTag(String.valueOf(i));
            if (i != currentFragmentIndex && fragment != null) {
                fragmentTransaction.hide(fragment);
            }
        }
        fragmentTransaction.commitAllowingStateLoss();
    }

    private Dialog dialog;

    private void showDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_choose_send, null);
        Button supplyOfGoods = (Button) view.findViewById(R.id.main_bt_send_supply_of_goods);
        supplyOfGoods.setOnClickListener(this);
        Button procurement = (Button) view.findViewById(R.id.main_bt_send_procurement);
        Button cancel = (Button) view.findViewById(R.id.main_bt_cancel);
        procurement.setOnClickListener(this);
        cancel.setOnClickListener(this);
        dialog = new Dialog(this, R.style.AppBaseTheme);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        Window window = dialog.getWindow();
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.MATCH_PARENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    private void dismissDialog() {
        if (null != dialog && dialog.isShowing())
            dialog.dismiss();
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.main_bt_send_supply_of_goods:
                //货源
                String supplierStatus = Settings.getSharedPreferences(Settings.SUPPLIER_STATUS);
                if (!"4".equals(supplierStatus)) {
                    Utils.showToast("请到我界面认证供应商！");
                    dismissDialog();
                    return;
                }
                dismissDialog();
                intent = new Intent(MainActivity.this, SendPublishedSourcesActivity.class);
                startActivity(intent);
                break;

            case R.id.main_bt_send_procurement:
                //采购
                dismissDialog();
                intent = new Intent(MainActivity.this, SendProcurementActivity.class);
                startActivity(intent);
                break;

            case R.id.main_bt_cancel:
                //取消
                dismissDialog();
                break;

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    public void onEventMainThread(SendMsgEvent event) {
        if (event.getSendType() == SendMsgEvent.EXIT_ACCOUNT) {
            finish();
        }
    }
}
